﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.ComponentModel.DataAnnotations;

namespace DeviceManager.Util
{
    public class ExcelUtil
    {
        public static byte[] BuildExcel(IEnumerable<object> source)
        {

            if (source != null && source.Any())
            {
                Application app = new Application();
                Workbook wbook = app.Workbooks.Add(true);

                Worksheet wsheet = wbook.ActiveSheet as Worksheet;
                object obj = source.FirstOrDefault();
                PropertyInfo[] infos = obj.GetType().GetProperties();
                int i = 0;
                foreach (var item in infos)
                {
                    var cutomeObj = item.GetCustomAttributes(typeof(DisplayAttribute), false);
                  
                    if (cutomeObj != null && cutomeObj.Any())
                    {

                        DisplayAttribute desc = cutomeObj[0] as DisplayAttribute;
                        wsheet.Cells[1, i + 1] = desc.Name;
                    }
                    else
                    {
                        wsheet.Cells[1, i + 1] = item.Name;
                    }
                    i++;
                }
                int j = 1;

                foreach (var item in source)
                {
                    i = 1;
                    PropertyInfo[] infoarr = item.GetType().GetProperties();
                    foreach (var info in infoarr)
                    {

                        var val = info.GetValue(item, null);
                        wsheet.Cells[j, i] = val;
                        i++;
                    }
                    j++;
                }

                //DateTime.Now
                //DateTime time = new DateTime();
                var path = HttpContext.Current.Server.MapPath("/Content/" + DateTime.Now.ToFileTime() + ".xls");
                wbook.SaveAs(path);

                //关闭工作表
                wbook.Close();
                //关闭工作薄
                //wbook.Close();
                //关闭应该程序
                app.Quit();
                FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[] bytes = new byte[input.Length];
                input.Read(bytes, 0, bytes.Length);
                input.Close();
                File.Delete(path);
                return bytes;
            }
            else
                throw new ArgumentNullException("source  can't  be  null");
        }
    }
}